package com.ahstu.learning.learning;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.ahstu.learning.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileManager extends ListActivity {
	private List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();
    private File currentDirectory;
    private File myTmpFile = null;
    private int myTmpOpt = -1;
    private String subject;

    @Override
    public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
        subject = getIntent().getStringExtra("subject");
        currentDirectory = new File("/sdcard/diandixuetang/" + subject + "/");
        browseToRoot();
        this.setSelection(0);
		
		
	}

	// 浏览文件系统的根目录
	private void browseToRoot() {
        browseTo(new File("/sdcard/diandixuetang/" + subject + "/"));
    }

	private void browseTo(final File file) {

		System.out.println(file.getAbsolutePath());
		this.setTitle(file.getAbsolutePath());
		if (file.isDirectory()) {
			this.currentDirectory = file;
			fill(file.listFiles());
		} else {
			fileOptMenu(file);
		}
	}

	// 打开指定文件
	protected void openFile(File aFile) {
		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		File file = new File(aFile.getAbsolutePath());
		// 取得文件名
		String fileName = file.getName();
		// 根据不同的文件类型来打开文件
		if (checkEndsWithInStringArray(fileName,
				getResources().getStringArray(R.array.fileEndingImage))) {
			intent.setDataAndType(Uri.fromFile(file), "image/*");
		} else if (checkEndsWithInStringArray(fileName, getResources()
				.getStringArray(R.array.fileEndingAudio))) {
			intent.setDataAndType(Uri.fromFile(file), "audio/*");
		} else if (checkEndsWithInStringArray(fileName, getResources()
				.getStringArray(R.array.fileEndingVideo))) {
			intent.setDataAndType(Uri.fromFile(file), "video/*");
		}
		startActivity(intent);
	}

	// 这里可以理解为设置ListActivity的源
	private void fill(File[] files) {
		// 清空列表
		this.directoryEntries.clear();

		Drawable currentIcon = null;
		for (File currentFile : files) {
			// 判断是一个文件夹还是一个文件
			if (currentFile.isDirectory()) {
				currentIcon = getResources()
						.getDrawable(R.drawable.file_folder);
			} else {
				// 取得文件名
				String fileName = currentFile.getName();
				// 根据文件名来判断文件类型，设置不同的图标
				if (checkEndsWithInStringArray(fileName, getResources()
						.getStringArray(R.array.fileEndingImage))) {
					currentIcon = getResources().getDrawable(
							R.drawable.file_image);
				} else if (checkEndsWithInStringArray(fileName, getResources()
						.getStringArray(R.array.fileEndingVideo))) {
					currentIcon = getResources().getDrawable(
							R.drawable.file_video);
				} else {
					currentIcon = getResources().getDrawable(
							R.drawable.file_text);
				}
			}
			// 确保只显示文件名、不显示路径如：/sdcard/111.txt就只是显示111.txt
			int currentPathStringLenght = this.currentDirectory
					.getAbsolutePath().length();
			this.directoryEntries.add(new IconifiedText(currentFile
					.getAbsolutePath().substring(currentPathStringLenght),
					currentIcon));
		}
		Collections.sort(this.directoryEntries);
		IconifiedTextListAdapter itla = new IconifiedTextListAdapter(this);
		// 将表设置到ListAdapter中
		itla.setListItems(this.directoryEntries);
		// 为ListActivity添加一个ListAdapter
		this.setListAdapter(itla);
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// 取得选中的一项的文件名
		String selectedFileString = this.directoryEntries.get(position)
				.getText();

		File clickedFile = null;
		clickedFile = new File(this.currentDirectory.getAbsolutePath()
				+ this.directoryEntries.get(position).getText());
		if (clickedFile != null)
			this.browseTo(clickedFile);
	}

	// 通过文件名判断是什么类型的文件
	private boolean checkEndsWithInStringArray(String checkItsEnd,
											   String[] fileEndings) {
		for (String aEnd : fileEndings) {
			if (checkItsEnd.endsWith(aEnd))
				return true;
		}
		return false;
	}

	// 删除文件
	public boolean deleteFile(File file) {
		boolean result = false;
		if (file != null) {
			try {
				File file2 = file;
				file2.delete();
				result = true;
			} catch (Exception e) {
				e.printStackTrace();
				result = false;
			}
		}
		return result;
	}

	// 处理文件，包括打开，重命名等操作
	public void fileOptMenu(final File file) {
		OnClickListener listener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 0) {
					openFile(file);
				} else if (which == 1) {
					Builder builder = new Builder(FileManager.this);
					builder.setTitle("删除文件");
					builder.setMessage("确定删除" + file.getName() + "？");
					builder.setPositiveButton(android.R.string.ok,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
													int which) {
									if (deleteFile(file)) {
										Builder builder = new Builder(
												FileManager.this);
										builder.setTitle("提示对话框");
										builder.setMessage("删除成功");
										builder.setPositiveButton(
												android.R.string.ok,
												new AlertDialog.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int which) {
														// 点击确定按钮之后
														dialog.cancel();
														browseTo(new File(
																GetCurDirectory()));
													}
												});
										builder.setCancelable(false);
										builder.create();
										builder.show();
									} else {
										Builder builder = new Builder(
												FileManager.this);
										builder.setTitle("提示对话框");
										builder.setMessage("删除失败");
										builder.setPositiveButton(
												android.R.string.ok,
												new AlertDialog.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int which) {
														// 点击确定按钮之后
														dialog.cancel();
													}
												});
										builder.setCancelable(false);
										builder.create();
										builder.show();
									}
								}
							});
					builder.setNegativeButton(android.R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
													int which) {
									dialog.cancel();
								}
							});
					builder.setCancelable(false);
					builder.create();
					builder.show();
				}
			}
		};
		// 显示操作菜单
		String[] menu = {"打开", "删除"};
		new AlertDialog.Builder(FileManager.this).setTitle("请选择你要进行的操作")
				.setItems(menu, listener).show();
	}

	// 得到当前目录的绝对路劲
	public String GetCurDirectory() {
		return this.currentDirectory.getAbsolutePath();
	}

}
